import 'package:flutter/material.dart';

//页面跳转并返回数据

//1、声明数据结构类
class Car {
  String brand;
  String color;

  Car(this.brand, this.color);
}

//2、第一个页面组件（父页面）
class FirstPageWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("FirstPageWidget"),
      ),
      body: Center(
        child: RaisedButtonWidget()
      ),
    );
  }
}

//选择按钮组件
class RaisedButtonWidget extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return RaisedButton(
        onPressed: () {
          this.ToSecondPageWidget(context);
        },
        child: Text("去选择"));
  }

  //路由到第二个页面，并等待返回。async是启用异步方法
  void ToSecondPageWidget(BuildContext context) async {
    //await等待结果返回
    final result = await Navigator.push(
        context, MaterialPageRoute(builder: (context) => SecondPageWidget()));
    Scaffold.of(context).showSnackBar(SnackBar(content: Text("$result")));
  }
}

//3、第二个页面组件（子页面）
class SecondPageWidget extends StatelessWidget {
  List<Car> carList = [Car("劳斯莱斯", "金黄色"), Car("兰博基尼", "大红色")];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("SecondPageWidget"),
      ),
      body: Center(
        child: ListView.builder(
            itemCount: carList.length,
            itemBuilder: (context, index) {
              return ListTile(
                title: Text(carList[index].brand),
                subtitle: Text(carList[index].color),
                onTap: () {
                  Navigator.pop(context, "选择了:" + carList[index].color + "的" + carList[index].brand);
                },
              );
            }),
      ),
    );
  }
}
